<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
    </el-form-item>

    <el-form-item label="品牌">
      <el-select v-model="spuForm.tmId">
        <el-option
          :value="(tm.id as number)"
          :label="tm.tmName"
          v-for="(tm, index) in trademarkList"
          :key="tm.id"
        >
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="SPU描述">
      <el-input
        placeholder="SPU描述"
        type="textarea"
        rows="4"
        v-model="spuForm.description"
      ></el-input>
    </el-form-item>
 
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="(spuImageList as any)"
        action="/app-dev/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select
        :placeholder="
          unUsedSaleAttrList.length
            ? `还有${unUsedSaleAttrList.length}未选择`
            : '没有啦！！！'
        "
        v-model="saleAttrIdName"
      >
        <el-option
          :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
          :label="unUsedSaleAttr.name"
          v-for="(unUsedSaleAttr, index) in unUsedSaleAttrList"
          :key="unUsedSaleAttr.id"
        ></el-option>
      </el-select>
      <el-button type="primary"  @click="addSaleAttr" :disabled="!saleAttrIdName">添加销售属性</el-button>
      <el-table :data="spuSaleAttrList" border stripe>
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row, $index }">
            <el-tag
              v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index,1)"
            >
              {{ saleAttrValue.saleAttrValueName }}
            </el-tag>
            <el-input
				@keyup.enter="$event.target.blur()"
				@blur="handleInputConfirm(row)"
				v-model="row.saleAttrValueName" 
				v-if="row.isEdit" 
				ref="InputRef" 
				class="ml-1 w-20" 
				size="small" 
				style="width: 100px;"/>
            <el-button  @click="showInput(row)" v-else class="button-new-tag ml-1" size="small">
              添加
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
            <template v-slot="{ row, $index }">
				<el-button
                    @click="spuSaleAttrList.splice($index,1)"
					type="danger"
					size="small"
					icon="ele-Delete"
					title="删除销售属性"
                    
				></el-button>
			</template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
			<el-button type="primary" @click="save" >保存</el-button>
			<el-button @click="emits('changeState',1)">取消</el-button>
		</el-form-item>
  </el-form>
</template>

<script lang="ts">

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
import type {
  BaseSaleAttrData,
  ResponseData,
  SpuData,
  SpuImageData,
  SpuSaleAttrData,
} from "@/api/spu";
import { Plus } from "@element-plus/icons-vue";
import { defineComponent, useCssModule } from "vue";
import { cloneDeep } from "lodash";
import { ElMessage, type UploadProps } from "element-plus";
import { ref, onMounted, computed,nextTick } from "vue";
import spuApi from "@/api/spu";
import skuApi from "@/api/sku";
import trademarkApi, { type TrademarkData } from "@/api/trademark";
import { useCategoryStore } from "@/stores/category";

// 父组件传递的数据让子组件使用

const props = defineProps<{ spu: SpuData }>();

const emits = defineEmits(['changeState'])
// 将接收到的row拷贝一份
const spuForm = ref(cloneDeep(props.spu));

// 发请求获取到初始化数据
const baseSaleAttrList = ref<BaseSaleAttrData[]>([]);
const trademarkList = ref<TrademarkData[]>([]);
const spuImageList = ref<SpuImageData[]>([]);
const spuSaleAttrList = ref<SpuSaleAttrData[]>([]);

const getInitAddSpuFormData = async () => {
  const promise1 = spuApi.getBaseSaleAttrList();
  // 获取所有的品牌列表
  // http://localhost:3000/app-dev/admin/product/baseTrademark/getTrademarkList
  const promise2 = trademarkApi.getList();

  try {
    const result = await Promise.all([promise1, promise2]);
    baseSaleAttrList.value = result[0];
    trademarkList.value = result[1];
    console.log(trademarkList.value);
  } catch (error) {
    ElMessage.error("获取初始化数据失败");
  }
};
const getInitUpdateSpuFormData = async () => {
  // 获取所有的销售属性列表
  // http://localhost:3000/app-dev/admin/product/baseSaleAttrList
  const promise1 = spuApi.getBaseSaleAttrList();
  // 获取所有的品牌列表
  // http://localhost:3000/app-dev/admin/product/baseTrademark/getTrademarkList
  const promise2 = trademarkApi.getList();
  // 根据spuid获取spu图片列表
  // http://localhost:3000/app-dev/admin/product/spuImageList/5339
  const promise3 = skuApi.getSpuImageList(spuForm.value.id as number);
  // 根据spuid获取spu自己的销售属性列表
  // http://localhost:3000/app-dev/admin/product/spuSaleAttrList/5339
  const promise4 = skuApi.getSpuSaleAttrList(spuForm.value.id as number);

  // Promise.all是一个方法，方法的本质就是函数，函数就要知道三要素
  // 功能：同时处理多个promise
  // 参数：promise对象的数组
  // 返回值：一个新的promise
  //  如果数组当中所有的promise都是成功的，那么返回的promise就是成功的，
  //  成功的结果是所有的数组当中promise成功的结果组成的数组
  //  如果数组当中有一个promise是失败的，那么返回的promise就是失败的
  //  失败的原因就是数组当中第一个失败的promise失败的原因
  try {
    const result = await Promise.all([promise1, promise2, promise3, promise4]);
    baseSaleAttrList.value = result[0];
    trademarkList.value = result[1];

    // 把请求回来的spu图片列表每个图片添加name和url，为了upload照片墙组件可以展示
    let imgList = result[2];
    imgList.forEach((item) => {
      item.name = item.imgName;
      item.url = item.imgUrl;
    });
    spuImageList.value = imgList;
    spuSaleAttrList.value = result[3];
  } catch (error) {
    ElMessage.error("获取初始化数据失败");
  }
};
// const add = async ()=>{
//      let adddd = await trademarkApi.getList()
//      console.log(adddd)
// }
onMounted(() => {
  if (spuForm.value.id) {
    getInitUpdateSpuFormData();
  } else {
    getInitAddSpuFormData();
  }
});
// 通过所有的销售属性列表和spu自己的销售属性列表计算未选择的销售属性列表
// 从所有的属性列表当中去过滤，不在spu自己的销售属性列表当中的项
// const unUsedSaleAttrList = computed(() => {
//   return baseSaleAttrList.value.filter((item) => {
//     return spuSaleAttrList.value.every((item1) => {
//       return item1.saleAttrName !== item.name;
//     });
//   });
// });
const unUsedSaleAttrList = computed(() => { 
    return baseSaleAttrList.value.filter((item)=>{
        return spuSaleAttrList.value.every((item1)=>{
            return item1.saleAttrName !== item.name
        })
    })
 })

// 拷贝的upload逻辑
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
//   spuImageList.value = uploadFiles as any
spuImageList.value = uploadFiles as any
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};


// 上传图片成功的回调
const handleSuccess:UploadProps["onSuccess"]= (response, uploadFile, uploadFiles) => {
	// console.log(response, uploadFile, uploadFiles);
	spuImageList.value = uploadFiles as any
    console.log(spuImageList.value)
}


// 收集添加销售属性
const saleAttrIdName = ref('')
const addSaleAttr = () => {
	// 把刚才收集到的串构造成需要的对象，push到spuSaleAttrList
	let [baseSaleAttrId,saleAttrName] = saleAttrIdName.value.split(':')
	let obj = {
		baseSaleAttrId,
		saleAttrName,
		spuSaleAttrValueList:[]
	}
	spuSaleAttrList.value.push(obj)
	saleAttrIdName.value = ''
}




// 收集添加销售属性值逻辑
const InputRef = ref()
const showInput = (row:SpuSaleAttrData) => {
	row.isEdit = true
	// 自动获取焦点
	nextTick(() => {
		InputRef.value.focus()
	})
}

// 输入完数据失去焦点
const handleInputConfirm = (row:SpuSaleAttrData) => {
	let {baseSaleAttrId,saleAttrValueName} = row

	if(!saleAttrValueName || !saleAttrValueName.trim()){
		ElMessage.error('请输入合法数据！')
		row.saleAttrValueName = ''
		row.isEdit = false
		return 
	}

	let isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName === saleAttrValueName)
	if(isRepeat){
		ElMessage.error('属性值名称不能重复')
		row.saleAttrValueName = ''
		row.isEdit = false
		return 
	}

	let obj = {baseSaleAttrId,saleAttrValueName}
	row.spuSaleAttrValueList.push(obj)
	row.saleAttrValueName = ''
	row.isEdit = false
}
// 保存操作
const categoryStore = useCategoryStore()
const save = async()=> {
    let spu = spuForm.value
    spu.category3Id = categoryStore.category3Id
    // console.log(spu.spuImageList)
    // 整理spu的图片列表
    spu.spuImageList = spuImageList.value.map(item=>{
        return {
            imgName:item.name,
            imgUrl:item.imgUrl || (item.response as ResponseData) .data 
        }
    })
    console.log(spuSaleAttrList.value)
    // 整理spu的销售列表
    spuSaleAttrList.value.forEach(item=>{
        delete item.isEdit
        delete item.saleAttrValueName
    })
    spu.spuSaleAttrList = spuSaleAttrList.value
    try {
      await spuApi.addOrUpdate(spu)
        ElMessage.success('保存spu成功')
        emits('changeState',1)  
    } catch (error) {
        ElMessage.error('保存spu失败')
    }
}
// 保存操作
// const categoryStore = useCategoryStore()
// const save = async ()=> {
//     let spu = spuForm.value
//     spu.category3Id = categoryStore.category3Id
//     // 整理spu的图片列表
//     spu.spuImageList = spuImageList.value.map(item=>{
//         return {
//             imgName:item.name,
//             imgUrl: item.imgUrl || (item.response as ResponseData).data
//         }
//     })
//     // 整理spu的销售列表
//     spuSaleAttrList.value.forEach(item=>{
//         delete item.isEdit
//         delete item.saleAttrValueName
//     }) // 将之前定义的自定义属性全部删掉
//     spu.spuSaleAttrList = spuSaleAttrList.value
//     // 发请求
//     try {
//         await spuApi.addOrUpdate(spu)
//         ElMessage.success('保存spu成功')
//         emits('changeState',1)
//     } catch (error) {
//         ElMessage.error('保存spu败败')
//     }
// }
</script>

<style lang="less" scoped></style>
